package com.hjx.windowtool.video;

import java.awt.EventQueue;
import java.awt.datatransfer.DataFlavor;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;

import javax.swing.JFrame;
import javax.swing.JSplitPane;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.hjx.windowtool.db.Tool;
import com.hjx.windowtool.util.MyAppender;

import lombok.extern.slf4j.Slf4j;

import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.util.List;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

@Slf4j
@Tool("获取信息")
public class GetNameByPlateApp {

	private JFrame frame;
	private JTextField txt_plate;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		File file = new File("F:\\Downloads\\cen");
		for (File f : file.listFiles()) {
			String name = f.getName();
			String substring = name.substring(0, 1).toUpperCase();
			if (substring.matches("[0-9A-Z]")) {
				continue;
			}
			String[] split = name.split("-");
			String s=split[1]+"-"+split[2];
			if (split[3].length()==1) {
				s+="-"+split[3];
			}
			f.renameTo(new File(f.getParent(),s+name.substring(name.lastIndexOf('.'))));
		}
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					GetNameByPlateApp window = new GetNameByPlateApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public GetNameByPlateApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JSplitPane splitPane = new JSplitPane();
		splitPane.setResizeWeight(0.5);
		splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
		frame.getContentPane().add(splitPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		splitPane.setLeftComponent(panel);
		panel.setLayout(null);
		
		JButton button = new JButton("测试");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				button.setEnabled(false);
				getFilesInfo(txt_plate.getText());
				button.setEnabled(true);
			}
		});
		button.setBounds(41, 53, 93, 23);
		panel.add(button);
		
		txt_plate = new JTextField();
		txt_plate.setBounds(41, 18, 200, 21);
		panel.add(txt_plate);
		txt_plate.setColumns(10);
		new DropTarget(txt_plate, DnDConstants.ACTION_COPY_OR_MOVE, new DropTargetAdapter() {
			@Override
			public void drop(DropTargetDropEvent dtde) {
				try {
					if (dtde.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
					    // 接收拖拽目标数据
					    dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);

					    // 以文件集合的形式获取数据
					    List<File> files = (List<File>) dtde.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);

					    // 把文件路径输出到文本区域
					    if (files != null && files.size() > 0) {
					        StringBuilder filePaths = new StringBuilder();
					        for (File file : files) {
					            filePaths.append(";" + file.getAbsolutePath());
					        }
					        filePaths.deleteCharAt(0);
					        txt_plate.setText(filePaths.toString());
					        dtde.dropComplete(true);
					    }
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}, true);
		
		JScrollPane scrollPane = new JScrollPane();
		splitPane.setRightComponent(scrollPane);
		
		JTextArea txt_msg = new JTextArea();
		scrollPane.setViewportView(txt_msg);
		
		MyAppender.list.add(new MyAppender.LogCallback() {
			@Override
			public void log(String s) {
				txt_msg.append(s);
			}
		});
	}

	protected void getFilesInfo(String s) {
		String[] split = s.split(";");
		for (String string : split) {
			getFileInfo(new File(string));
		}
	}

	private void getFileInfo(File file) {
		if (!file.exists()) {
			return;
		}
		if (file.isDirectory()) {
			for (File f : file.listFiles()) {
				getFileInfo(f);
			}
		}else {
			String name = file.getName ();
			name=name.substring(0, name.lastIndexOf('.')).toUpperCase();
			String start = name.substring(0, 1).toUpperCase();
			if (!start.matches("[0-9A-Z]")) {
				return;
			}
			String[] split = name.split("-");
			if (split.length<2) {
				return;
			}
			String plate = split[0]+"-"+split[1];
			String[] plateName = getPlateInfo(plate);
			String newFileName = plateName[0]+"-"+name+"-"+plateName[1].replace(plate, "").trim();
			file.renameTo(new File(file.getParent(),newFileName+file.getName().substring(file.getName().lastIndexOf("."))));
			downloadImage(plateName[2], new File(file.getParent(),newFileName+".jpg"));
		}
		
	}
	
	public boolean downloadImage(String url,File file) {
		try {
			log.info("下载图片{}",url);
			HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
			conn.setDoInput(true);
			InputStream is = conn.getInputStream();
			try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
				byte[] b = new byte[1024];
				int read = -1;
				while ((read = is.read(b)) > 0) {
					bos.write(b, 0, read);
				}
				Files.write(file.toPath(), bos.toByteArray());
				log.info("下载图片:{}完成,保存位置：{}",url,file);
				return true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("下载图片时发生错误",e);
		}
		return false;
	}

	protected String[] getPlateInfo(String plate) {
		log.info("获取车牌：{}信息",plate);
		String[] info=null;
		try {
			Document d = Jsoup.connect("https://avmask.com/cn/search/"+plate).get();
			Elements select = d.select("div.item");
			if (select.isEmpty()) {
				return null;
			}
			String href = select.select("a[href]").attr("href");
			System.out.println(href);
			for (Element e : select) {
				System.out.println(e);
			}
//			System.out.println(d);
			System.out.println("==============");
			Document detail = Jsoup.connect(href).get();
			
//			System.out.println(detail);
			String name = detail.select("div#avatar-waterfall").select("span").text();
			System.out.println(name);
			Elements bigImage = detail.select("a.bigImage");
			String imghref = bigImage.attr("href");
			String title = bigImage.attr("title");
			System.out.println(imghref);
			System.out.println(title);
			log.info("车牌信息：{}-{}-{}",name,title,imghref);
			info=new String[] {name,title,imghref};
		} catch (Exception e) {
			log.error("获取车牌信息时发生错误",e);
		}
		return info;
	}
}
